package com.dudy.authdemo.controller;

import com.alibaba.fastjson.JSONObject;
import com.dudy.authdemo.model.Role;
import com.dudy.authdemo.service.RoleService;
import com.dudy.authdemo.vo.RoleVO;
import com.dudy.common.base.CommonResponse;
import com.dudy.common.base.PageData;
import com.dudy.common.base.ResultCode;
import com.dudy.common.util.DingTalkUtil;
import com.dudy.common.util.ResponseUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

/**
 * @program: auth_demo
 * @author: dudy
 * @create: 2020-12-24 10:43
 * @description:
 **/
@RestController
@RequestMapping("/role")
public class RoleController {

    private static final Logger log = LoggerFactory.getLogger(RoleController.class);

    @Autowired
    private RoleService roleService;

    @PostMapping("/addRole")
    public CommonResponse<RoleVO> addRole(RoleVO roleVO) {
        if (roleVO == null) {
            return ResponseUtils.getResponse(ResultCode.REQUEST_PARAM_NULL);
        }
        Role role = new Role();
        BeanUtils.copyProperties(roleVO, role);
        role.setCreator(((User)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername());
        role.setUpdater(((User)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername());
        role.setGmtCreateTime(new Date());
        role.setGmtUpdateTime(new Date());
        role.setDeleteFlag((byte) 0);
        try {
            int insert = roleService.insert(role);
            if (insert == 1) {
                return ResponseUtils.getResponse(ResultCode.SUCCESS);
            } else {
                return ResponseUtils.getResponse(ResultCode.FAIL.getCode(), "操作失败，请重试");
            }
        } catch (Exception e) {
            log.error("RoleController addRole error,请求参数：{}", JSONObject.toJSONString(roleVO), e);
            DingTalkUtil.pushError("auth_demo", this.getClass().getName(), "addRole", JSONObject.toJSONString(roleVO)
                    , e);
            return ResponseUtils.getResponse(ResultCode.FAIL);
        }
    }

    @PostMapping("/updateRole")
    public CommonResponse<RoleVO> updateRole(RoleVO roleVO) {
        if (roleVO == null || roleVO.getId() == null) {
            return ResponseUtils.getResponse(ResultCode.REQUEST_PARAM_NULL);
        }
        Role role = new Role();
        BeanUtils.copyProperties(roleVO, role);
        role.setUpdater(((User)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername());
        role.setGmtUpdateTime(new Date());
        try {
            int update = roleService.updateByPrimaryKey(role);
            if (update == 1) {
                return ResponseUtils.getResponse(ResultCode.SUCCESS);
            } else {
                return ResponseUtils.getResponse(ResultCode.FAIL.getCode(), "操作失败，请重试");
            }
        } catch (Exception e) {
            log.error("RoleController update error,请求参数：{}", JSONObject.toJSONString(roleVO), e);
            DingTalkUtil.pushError("auth_demo", this.getClass().getName(), "update", JSONObject.toJSONString(roleVO),
                    e);
            return ResponseUtils.getResponse(ResultCode.FAIL);
        }
    }

    @GetMapping("/queryRoleById")
    public CommonResponse<RoleVO> queryRoleById(@RequestParam("id") long id) {
        Role role = new Role();
        role.setId(id);
        try {
            RoleVO roleVO = roleService.selectByPrimaryKey(role);
            return ResponseUtils.getResponse(ResultCode.SUCCESS, roleVO);
        } catch (Exception e) {
            log.error("RoleController queryRoleById error,请求参数：{}", id, e);
            DingTalkUtil.pushError("auth_demo", this.getClass().getName(), "queryRoleById", id + "",
                    e);
            return ResponseUtils.getResponse(ResultCode.FAIL);
        }
    }

    @GetMapping("/queryRoleByExample")
    public CommonResponse<List<RoleVO>> queryRoleByExample(RoleVO roleVO) {
        Example example = new Example(Role.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("deleteFlag", 0);
        if (StringUtils.isNotBlank(roleVO.getRoleName())) {
            criteria.andLike("roleName", roleVO.getRoleName());
        }
        if (StringUtils.isNotBlank(roleVO.getRoleCode())) {
            criteria.andEqualTo("roleName", roleVO.getRoleCode());
        }
        try {
            List<RoleVO> roleVOS = roleService.selectByExample(example);
            return ResponseUtils.getResponse(ResultCode.SUCCESS, roleVOS);
        } catch (Exception e) {
            log.error("RoleController queryRoleByExample error,请求参数：{}", JSONObject.toJSONString(roleVO), e);
            DingTalkUtil.pushError("auth_demo", this.getClass().getName(), "queryRoleByExample",
                    JSONObject.toJSONString(roleVO) + "",
                    e);
            return ResponseUtils.getResponse(ResultCode.FAIL);
        }
    }

    /**
     * 精确匹配查询
     *
     * @param roleVO
     * @return
     */
    @GetMapping("/queryRoleExactly")
    public CommonResponse<List<RoleVO>> queryRoleExactly(RoleVO roleVO) {
        Example example = new Example(Role.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("deleteFlag", 0);
        if (StringUtils.isNotBlank(roleVO.getRoleName())) {
            criteria.andEqualTo("roleName", roleVO.getRoleName());
        }
        if (StringUtils.isNotBlank(roleVO.getRoleCode())) {
            criteria.andEqualTo("roleName", roleVO.getRoleCode());
        }
        try {
            List<RoleVO> roleVOS = roleService.selectByExample(example);
            return ResponseUtils.getResponse(ResultCode.SUCCESS, roleVOS);
        } catch (Exception e) {
            log.error("RoleController queryRoleExactly error,请求参数：{}", JSONObject.toJSONString(roleVO), e);
            DingTalkUtil.pushError("auth_demo", this.getClass().getName(), "queryRoleExactly",
                    JSONObject.toJSONString(roleVO) + "",
                    e);
            return ResponseUtils.getResponse(ResultCode.FAIL);
        }
    }

    @GetMapping("/queryRolePage")
    public CommonResponse<PageData<RoleVO>> queryRolePage(RoleVO roleVO) {
        Example example = new Example(Role.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("deleteFlag", 0);
        if (StringUtils.isNotBlank(roleVO.getRoleName())) {
            criteria.andLike("roleName", roleVO.getRoleName());
        }
        if (StringUtils.isNotBlank(roleVO.getRoleCode())) {
            criteria.andEqualTo("roleName", roleVO.getRoleCode());
        }
        try {
            PageData<RoleVO> pageData = roleService.selectPageByExample(roleVO, example);
            return ResponseUtils.getResponse(ResultCode.SUCCESS, pageData);
        } catch (Exception e) {
            log.error("RoleController queryRolePage error,请求参数：{}", JSONObject.toJSONString(roleVO), e);
            DingTalkUtil.pushError("auth_demo", this.getClass().getName(), "queryRolePage",
                    JSONObject.toJSONString(roleVO) + "",
                    e);
            return ResponseUtils.getResponse(ResultCode.FAIL);
        }
    }
}
